package com.buddy.learn.source._lock;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.openjdk.jol.info.ClassLayout;

/**
 * @author Buddy
 * @date 2021/4/26
 */
public class LockUpgrade {

    public static void main(String[] args) throws InterruptedException {
        User userTemp = new User();
        System.out.println("无锁状态(001)"+ ClassLayout.parseInstance(userTemp).toPrintable());
        /*
         * JVM 默认延迟 4s 自动开启偏向锁，可以通过 -XX:BiasedLockingStartupDelay=0 取消延时
         * 如果不要偏向锁，可以通过 -XX:UseBiasedLocking=false 设置
         */
        Thread.sleep(5*1000);
        User user = new User();
        System.out.println("启用偏向锁(101)"+ClassLayout.parseInstance(user).toPrintable());

        for (int i=0;i<2;i++){
            synchronized (user){
                System.out.println("偏向锁（101）（带线程id）："+ClassLayout.parseInstance(user).toPrintable());
            }
            System.out.println("偏向锁释放（101）（带线程id）："+ClassLayout.parseInstance(user).toPrintable());
        }

        new Thread(()->{
            synchronized (user){
                System.out.println("轻量级锁(00):"+ClassLayout.parseInstance(user).toPrintable());
            }
            try {
                System.out.println("睡眠 3s -------------------");
                Thread.sleep(3*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("轻量级锁 --> 重量级锁(10):"+ ClassLayout.parseInstance(user).toPrintable());
        }).start();
        Thread.sleep(1000);
        new Thread(()->{
            synchronized (user){
                System.out.println("重量级锁（10）："+ClassLayout.parseInstance(user).toPrintable());
            }
        }).start();

    }

}

@Data @AllArgsConstructor @NoArgsConstructor
class User{
    private int id;
    private String name;
}